package com.itheima.tliaswebmanagement.controller;

import com.itheima.tliaswebmanagement.pojo.Dept;
import com.itheima.tliaswebmanagement.pojo.Result;
import com.itheima.tliaswebmanagement.service.DeptService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Slf4j
@RequestMapping("/depts")
@RestController  //json格式返回数据
public class DeptController {

    @Autowired //调用service层
    private DeptService deptService;
    @GetMapping//(value = "/depts",method = RequestMethod.GET) //method用来指定请求方式。或者用@GetMapping("/dept")
    public Result list() {
        log.info("查询全部部门信息");
        List <Dept> deptList = deptService.findAll();
        return Result.success(deptList);
    }
    /*
    * 删除部门信息
    * */
    //方式一
/*    @DeleteMapping(value = "/depts")
    public Result delete(HttpServletRequest request) {
        String idStr = request.getParameter("id");
        int id=Integer.parseInt(idStr);
        System.out.println("删除id为"+id+"的部门信息");
        return Result.success();
    }*/
    //方式二
  /*  @DeleteMapping(value = "/depts")
    public Result delete(@RequestParam(value = "id",required = false)Integer deptId) {
        System.out.println("删除id为"+deptId+"的部门信息");
        return Result.success();
    }*/

    //方式三 前端传递的参数名和形参名一致，可以省略@RequestParam注解
    @DeleteMapping//(value = "/depts")
    public Result delete(Integer id) {
        //System.out.println("删除id为"+id+"的部门信息");
        log.info("删除id为{}的部门信息",id);
        deptService.deleteById(id);
        return Result.success();
    }

    @PostMapping//(value = "/depts")
    public Result add(@RequestBody Dept dept) { //@RequestBody将json格式的数据封装到java对象
        log.info("新增部门信息："+dept);
        deptService.add(dept);
        return Result.success();
    }


    /*@GetMapping(value = "/depts/{id}")//{}路径参数
    public Result getInfo(@PathVariable("id") Integer deptId){
        System.out.println("查询id为"+deptId+"的部门信息");
        return Result.success();
    }*/

    /*
    * 根据id查询部门信息
    * */
    @GetMapping(value = "/{id}")//{}路径参数
    public Result getInfo(@PathVariable Integer id){
        log.info("查询id为{}的部门信息",id);
        Dept dept=deptService.getById(id);
        return Result.success(dept);
    }

    /*修改部门*/
    @PutMapping//(value = "/depts")
    public Result update(@RequestBody Dept dept){
        log.info("修改部门信息："+dept);
        deptService.update(dept);
        return Result.success();
    }

}
